<html lang="en-US">

<head>
    
<title>「连载六」Unary and Stream interceptor - 花落雨忧</title>

<meta property="og:title" content="「连载六」Unary and Stream interceptor - 花落雨忧">



    



    
    <meta property="description" content="我想在每个 RPC 方法的前或后做某些事情，怎么做？
本章节将要介绍的拦截器（interceptor），就能帮你在合适的地方实现这些功能。
[&amp;hellip;] 在 gRPC 中，大类可分为两种 RPC 方法，与拦截器的对应关系是：
[&amp;hellip;] func UnaryInterceptor(i UnaryServerInterceptor) ServerOption { return &amp;hellip;">
    <meta property="og:description" content="我想在每个 RPC 方法的前或后做某些事情，怎么做？
本章节将要介绍的拦截器（interceptor），就能帮你在合适的地方实现这些功能。
[&amp;hellip;] 在 gRPC 中，大类可分为两种 RPC 方法，与拦截器的对应关系是：
[&amp;hellip;] func UnaryInterceptor(i UnaryServerInterceptor) ServerOption { return &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/grpc/2018-10-10-interceptor/">「连载六」Unary and Stream interceptor</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/10/10</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="前言">前言</h2>
<p>我想在每个 RPC 方法的前或后做某些事情，怎么做？</p>
<p>本章节将要介绍的拦截器（interceptor），就能帮你在合适的地方实现这些功能。</p>
<h2 id="有几种方法">有几种方法</h2>
<p>在 gRPC 中，大类可分为两种 RPC 方法，与拦截器的对应关系是：</p>
<ul>
<li>普通方法：一元拦截器（grpc.UnaryInterceptor）</li>
<li>流方法：流拦截器（grpc.StreamInterceptor）</li>
</ul>
<h2 id="看一看">看一看</h2>
<h3 id="grpcunaryinterceptor">grpc.UnaryInterceptor</h3>
<pre><code>func UnaryInterceptor(i UnaryServerInterceptor) ServerOption {
	return func(o *options) {
		if o.unaryInt != nil {
			panic(&quot;The unary server interceptor was already set and may not be reset.&quot;)
		}
		o.unaryInt = i
	}
}
</code></pre><p>函数原型：</p>
<pre><code>type UnaryServerInterceptor func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (resp interface{}, err error)
</code></pre><p>通过查看源码可得知，要完成一个拦截器需要实现 <code>UnaryServerInterceptor</code> 方法。形参如下：</p>
<ul>
<li>ctx context.Context：请求上下文</li>
<li>req interface{}：RPC 方法的请求参数</li>
<li>info *UnaryServerInfo：RPC 方法的所有信息</li>
<li>handler UnaryHandler：RPC 方法本身</li>
</ul>
<h3 id="grpcstreaminterceptor">grpc.StreamInterceptor</h3>
<pre><code>func StreamInterceptor(i StreamServerInterceptor) ServerOption
</code></pre><p>函数原型：</p>
<pre><code>type StreamServerInterceptor func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error
</code></pre><p>StreamServerInterceptor 与 UnaryServerInterceptor 形参的意义是一样，不再赘述</p>
<h3 id="如何实现多个拦截器">如何实现多个拦截器</h3>
<p>另外，可以发现 gRPC 本身居然只能设置一个拦截器，难道所有的逻辑都只能写在一起？</p>
<p>关于这一点，你可以放心。采用开源项目 <a href="https://github.com/grpc-ecosystem/go-grpc-middleware">go-grpc-middleware</a> 就可以解决这个问题，本章也会使用它。</p>
<pre><code>import &quot;github.com/grpc-ecosystem/go-grpc-middleware&quot;

myServer := grpc.NewServer(
    grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
        ...
    )),
    grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
       ...
    )),
)
</code></pre><h2 id="grpc">gRPC</h2>
<p>从本节开始编写 gRPC interceptor 的代码，我们会将实现以下拦截器：</p>
<ul>
<li>logging：RPC 方法的入参出参的日志输出</li>
<li>recover：RPC 方法的异常保护和日志输出</li>
</ul>
<h3 id="实现-interceptor">实现 interceptor</h3>
<h4 id="logging">logging</h4>
<pre><code>func LoggingInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	log.Printf(&quot;gRPC method: %s, %v&quot;, info.FullMethod, req)
	resp, err := handler(ctx, req)
	log.Printf(&quot;gRPC method: %s, %v&quot;, info.FullMethod, resp)
	return resp, err
}
</code></pre><h4 id="recover">recover</h4>
<pre><code>func RecoveryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
	defer func() {
		if e := recover(); e != nil {
			debug.PrintStack()
			err = status.Errorf(codes.Internal, &quot;Panic err: %v&quot;, e)
		}
	}()

	return handler(ctx, req)
}
</code></pre><h3 id="server">Server</h3>
<pre><code>import (
	&quot;context&quot;
	&quot;crypto/tls&quot;
	&quot;crypto/x509&quot;
	&quot;errors&quot;
	&quot;io/ioutil&quot;
	&quot;log&quot;
	&quot;net&quot;
	&quot;runtime/debug&quot;

	&quot;google.golang.org/grpc&quot;
	&quot;google.golang.org/grpc/credentials&quot;
	&quot;google.golang.org/grpc/status&quot;
	&quot;google.golang.org/grpc/codes&quot;
	&quot;github.com/grpc-ecosystem/go-grpc-middleware&quot;

	pb &quot;github.com/EDDYCJY/go-grpc-example/proto&quot;
)

...

func main() {
	c, err := GetTLSCredentialsByCA()
	if err != nil {
		log.Fatalf(&quot;GetTLSCredentialsByCA err: %v&quot;, err)
	}

	opts := []grpc.ServerOption{
		grpc.Creds(c),
		grpc_middleware.WithUnaryServerChain(
			RecoveryInterceptor,
			LoggingInterceptor,
		),
	}

	server := grpc.NewServer(opts...)
	pb.RegisterSearchServiceServer(server, &amp;SearchService{})

	lis, err := net.Listen(&quot;tcp&quot;, &quot;:&quot;+PORT)
	if err != nil {
		log.Fatalf(&quot;net.Listen err: %v&quot;, err)
	}

	server.Serve(lis)
}
</code></pre><h2 id="验证">验证</h2>
<h3 id="logging-1">logging</h3>
<p>启动 simple_server/server.go，执行 simple_client/client.go 发起请求，得到结果：</p>
<pre><code>$ go run server.go
2018/10/02 13:46:35 gRPC method: /proto.SearchService/Search, request:&quot;gRPC&quot; 
2018/10/02 13:46:35 gRPC method: /proto.SearchService/Search, response:&quot;gRPC Server&quot;
</code></pre><h3 id="recover-1">recover</h3>
<p>在 RPC 方法中人为地制造运行时错误，再重复启动 server/client.go，得到结果：</p>
<h4 id="client">client</h4>
<pre><code>$ go run client.go
2018/10/02 13:19:03 client.Search err: rpc error: code = Internal desc = Panic err: assignment to entry in nil map
exit status 1
</code></pre><h4 id="server-1">server</h4>
<pre><code>$ go run server.go
goroutine 23 [running]:
runtime/debug.Stack(0xc420223588, 0x1033da9, 0xc420001980)
	/usr/local/Cellar/go/1.10.1/libexec/src/runtime/debug/stack.go:24 +0xa7
runtime/debug.PrintStack()
	/usr/local/Cellar/go/1.10.1/libexec/src/runtime/debug/stack.go:16 +0x22
main.RecoveryInterceptor.func1(0xc420223a10)
...
</code></pre><p>检查服务是否仍然运行，即可知道 Recovery 是否成功生效</p>
<h2 id="总结">总结</h2>
<p>通过本章节，你可以学会最常见的拦截器使用方法。接下来其它“新”需求只要举一反三即可。</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-grpc-example">go-grpc-example</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-10-08-ca-tls/">「连载五」基于 CA 的 TLS 证书认证</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-10-07-grpc-tls/">「连载四」TLS 证书认证</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-09-24-stream-client-server/">「连载三」gRPC Streaming, Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-09-23-client-and-server/">「连载二」gRPC Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-09-22-install/">「连载一」gRPC及相关介绍</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/grpc" title="View all posts tagged match">grpc</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/grpc/2018-10-08-ca-tls/"
                                                    rel="prev">「连载五」基于 CA 的 TLS 证书认证</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/grpc/2018-10-12-grpc-http/">「连载七」让你的服务同时提供 HTTP 接口</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>